<template>
  <div class="bigBox">
    <div class="leftBox">
      <el-autocomplete
        class="inline-input"
        v-model="filterText"
        style="margin-bottom: 10px; width: 100%"
        :fetch-suggestions="querySearch"
        placeholder="输入关键字进行过滤"
        :trigger-on-focus="true"
        value-key="name"
        :debounce="300"
        @select="handleSelect"
      ></el-autocomplete>
      <el-tree
        class="filter-tree"
        :data="assetTreeList"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :default-expanded-keys="openKeys"
        node-key="id"
        lazy
        :load="loadNode"
        :highlight-current="true"
        ref="tree"
      >
        <span slot-scope="{ node, data }" class="slot-t-node">
          <template>
            <img
              :src="'data:image/png;base64,' + data.iconBase64"
              style="
                width: 16px;
                height: 16px;
                margin-right: 5px;
                vertical-align: bottom;
              "
            />
            <span style="font-size:14px!important">{{ node.label }}</span>
          </template>
        </span>
      </el-tree>
    </div>
    <div class="rightBox">
      <div class="rb-top">
        <TopBottom :nodeList="nodeList" @diaData="getdiaData" />
      </div>
      <div class="rb-bottom">
        <FaceRoot
          v-if="nodeList?.className !== 'Root'"
          ref="FaceRoot"
          :loading="loading"
          :formData="formData"
          :selectList="selectList"
          :form="form"
          :xianshi="false"
        />
      </div>
    </div>
    <el-dialog
      :title="title"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <FaceRoot
        ref="FaceRootDia"
        :loading="loading"
        :formData="formDataDia"
        :selectList="selectListDia"
        :form="formDia"
        :xianshi="true"
        :nodeList="nodeList"
      />
      <span slot="footer" class="dialog-footer" v-if="statu !== 'view'">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAssetTreeRootApi,
  getAssetDataApi,
  getFacerootApi,
  getViewDataApi,
  getAddDataApi,
  addEquipmentApi,
  editEquipmentApi,
  getEditDataApi,
  checkoutDataApi,
  delDataApi,
  getKeywordListApi
} from '@/api/Ledger2.js'
import TopBottom from '@/views/Ledger2/components/TopBottom'
import FaceRoot from '@/views/Ledger2/components/FaceRoot'
export default {
  name: 'LedgerIndex',
  components: { TopBottom, FaceRoot },
  data () {
    return {
      statu: '',
      restaurants: [],
      assetTreeList: [],
      nodeList: {},
      filterText: '',
      formData: {},
      diaData: {},
      openKeys: [],
      form: {},
      formdia: {},
      selectList: {},
      defaultProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'leaf'
      },
      loading: false,
      isshow: false,
      title: '',
      formDataDia: {},
      selectListDia: {},
      dialogVisible: false,
      currentId: '',
      event: 'click'
    }
  },
  created () {
    this.getAssetTreeRoot()
  },
  mounted () {},
  watch: {
    filterText (newValue) {
      this.filterText = newValue
        .replace(/^\[(.*?)\]/, '')
        .replace(/\((.*?)\)$/, '')
    }
  },
  methods: {
    async getAssetTreeRoot () {
      const res = await getAssetTreeRootApi()
      console.log(res?.data.list[0])
      // this.assetTreeList = res?.data.list[0]
      const res1 = await getAssetDataApi(res?.data.list[0])
      this.assetTreeList = res1.data.list
      console.log('res1', res1)
    },
    async chushihua (className) {
      this.handleClose()
      this.loading = true
      const res = await getFacerootApi({
        className: className
      })
      if (className !== 'Root') {
        const res1 = await getViewDataApi({
          entityId: this.nodeList.entityId,
          className: className
        })
        this.formData = res1?.data.entity?.valueMap
        this.selectList = res1?.data.entity?.elementComboItemMap
      }
      this.form = res.data.entity
      console.log(res)
      console.log('form', this.form)
      this.loading = false
    },
    async chushihuaDia (className) {
      this.handleClose()
      this.loading = true
      const res = await getFacerootApi({
        className: className
      })
      this.formDia = res?.data.entity
      if (this.nodeList.className !== 'Root') {
        const res1 = await getViewDataApi({
          entityId: this.nodeList.entityId,
          className: className
        })
        this.$nextTick(() => {
          // this.formDataDia = res1?.data.entity?.valueMap
          this.selectListDia = res1?.data.entity?.elementComboItemMap
        })
      }
      this.loading = false
    },
    load (e) {
      this.loading = e
    },
    async loadNode (node, resolve) {
      if (node.level > 0) {
        const res = await getAssetDataApi(node.data)
        return resolve(res?.data.list)
      }
    },
    // 树节点搜索
    async querySearch (queryString, cb) {
      const res = await getKeywordListApi({ name: queryString })
      const restaurants = res.data.list
      cb(restaurants)
      // 调用 callback 返回建议列表的数据
    },
    // 搜索选择
    handleSelect (item) {
      this.event = 'select'
      console.log(item)
      this.openKeys = item.pathId.split(',')
      this.openKeys.shift()
      this.openKeys.unshift(this.assetTreeList[0]?.id)
      function setCurrentKey (that) {
        const node = that.$refs.tree.getNode(item)
        if (node) {
          that.$refs.tree.setCurrentKey(item.id)
          that.form = {}
          that.handleClose()
          that.nodeList = node.data
          that.node = node
          if (node.data.className !== 'Root') {
            that.chushihua(that.nodeList.className)
          }
        } else {
          setTimeout(() => {
            setCurrentKey(that)
          }, 500)
        }
      }
      setCurrentKey(this)
      // console.log(node)
    },
    createFilter (queryString) {
      return (restaurant) => {
        console.log(restaurant)
        return (
          restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
      }
    },
    // 树节点点击
    async handleNodeClick (val, node) {
      this.event = 'click'
      console.log('nodeList', val)
      this.form = {}
      this.handleClose()
      this.nodeList = val
      this.node = node
      if (val.className !== 'Root') {
        this.chushihua(this.nodeList.className)
      }
    },
    refreshNode (key) {
      // 获取当前节点，key可以在@node-click和:load绑定函数的回调参数node用变量存储后有需要刷新的地方取node.key
      const node = this.$refs.tree.getNode(key)
      //  设置未进行懒加载状态
      console.log('loaded', node)
      node.loaded = false
      // 重新展开节点就会间接重新触发load达到刷新效果
      node.expand()
      this.nodeList = node.data
      console.log('nn', this.nodeList)
    },
    async getdiaData (item) {
      console.log('按钮属性', item)
      if (item.contextmenuType === 'CreateDevice') {
        this.statu = 'add'
        this.title = item.contextmenuName
        this.loading = true
        this.chushihuaDia(item.className)
        if (this.nodeList.className === 'Root') {
          this.diaData = {
            className: item.className,
            name: item.contextmenuName
          }
        } else {
          this.diaData = {
            className: item.className,
            parentClassName: this.nodeList.className,
            parentId: this.nodeList.entityId,
            name: item.contextmenuName
          }
        }
        const res = await getAddDataApi(this.diaData)
        this.formDataDia = res?.data.entity?.valueMap
        this.selectListDia = res?.data.entity?.elementComboItemMap
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.FaceRootDia.preview = false
        })
        this.loading = false
      } else if (item.contextmenuType === 'ViewDevice') {
        this.statu = 'view'
        this.title = item.contextmenuName + `[${this.nodeList.entityId}]`
        this.loading = true
        this.chushihuaDia(this.nodeList.className)
        const res = await getEditDataApi({
          entityId: this.nodeList.entityId,
          className: this.nodeList.className
        })
        this.formDataDia = res?.data.entity?.valueMap
        this.selectListDia = res?.data.entity?.elementComboItemMap
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.FaceRootDia.preview = true
          console.log(this.$refs.FaceRootDia.preview)
        })
        this.loading = false
      } else if (item.contextmenuType === 'ModifyDevice') {
        this.statu = 'edit'
        this.title = item.contextmenuName + `[${this.nodeList.entityId}]`
        this.loading = true
        console.log('修改', item)
        this.chushihuaDia(this.nodeList.className)
        const res = await getEditDataApi({
          entityId: this.nodeList.entityId,
          className: this.nodeList.className
        })
        this.formDataDia = res?.data.entity?.valueMap
        this.selectListDia = res?.data.entity?.elementComboItemMap
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.FaceRootDia.preview = false
          console.log(this.$refs.FaceRootDia.preview)
        })
        this.loading = false
      } else if (item.contextmenuType === 'RemoveDevice') {
        this.statu = 'delete'
        console.log('delete')
        const res = await checkoutDataApi({
          entityId: this.nodeList.entityId,
          className: item.className
        })
        if (res.code == 200) {
          this.$confirm(
            `此操作将永久删除${this.nodeList.name}, 是否继续?`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(async () => {
              try {
                const res = await delDataApi({
                  entityId: this.nodeList.entityId,
                  className: item.className
                })
                if (res.code == 200) {
                  this.$message({
                    type: 'success',
                    message: '删除成功',
                    duration: 2000
                  })
                }
                this.refreshNode(this.node.parent.key)
                this.form = {}
                this.chushihua(this.nodeList.className)
              } catch (err) {
                this.$message({
                  type: 'error',
                  message: '删除失败',
                  duration: 2000
                })
              }
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除',
                duration: 2000
              })
            })
        } else {
          this.$message({
            type: 'error',
            message: res.message,
            duration: 2000
          })
        }
      }
    },
    handleClose () {
      this.dialogVisible = false
      this.formDataDia = {}
      this.selectListDia = {}
      // this.formData = {}
      this.selectList = {}
    },
    async submit () {
      // if (this.$refs.FaceRootDia.valid()) {
      if (this.statu === 'add') {
        const data = this.$refs.FaceRootDia.handleGetAllData()
        console.log('adddata', data)
        const res =
          this.nodeList.className === 'Root'
            ? await addEquipmentApi({
              className: data.CLASSNAME,
              valueMapJson: JSON.stringify(data)
            })
            : await addEquipmentApi({
              className: data.CLASSNAME,
              parentClassName: this.nodeList.className,
              parentId: this.nodeList.entityId,
              valueMapJson: JSON.stringify(data)
            })
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '新增成功',
            duration: 2000
          })
          // this.form = {}
          // const res = await getAssetDataApi(this.nodeList)
          // this.node.children = res.data.list
          console.log(this.assetTreeList)
          console.log('-----', this.node)
          this.refreshNode(this.node.key)
          this.form = {}
          this.handleClose()
          this.chushihua(this.nodeList.className)
        } else {
          this.$message({
            type: 'error',
            message: '新增失败',
            duration: 2000
          })
        }
      } else if (this.statu === 'edit') {
        const data = this.$refs.FaceRootDia.handleGetAllData()
        console.log('editdata', data)
        const res = await editEquipmentApi({
          className: data.CLASSNAME,
          entityId: this.nodeList.entityId,
          valueMapJson: JSON.stringify(data)
        })
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '修改成功',
            duration: 2000
          })
          // const res = await getAssetDataApi(this.nodeList)
          // this.node.children = res.data.list
          console.log('node', this.node)
          // const node = this.node
          this.form = {}
          if (this.node.level !== 1) {
            this.refreshNode(this.node.parent.key)
            this.refreshNode(this.node.key)
          } else {
            await this.getAssetTreeRoot()
            this.refreshNode(this.node.key)
          }
          setTimeout(() => {
            this.$refs.tree.setCurrentKey(this.node.key)
          }, 300)
          this.chushihua(this.nodeList.className)
          this.handleClose()
        } else {
          this.$message({
            type: 'error',
            message: '修改失败',
            duration: 2000
          })
        }
      }
    }
    // }
  }
}
</script>

<style lang="scss" scoped>
.bigBox {
  display: flex;
  padding: 10px;
  height: 100vh;
  box-sizing: border-box;
  .leftBox {
    margin-right: 10px;
    padding: 20px 10px;
    height: 100%;
    width: 300px;
    overflow: auto;
    background-color: #fff;
    box-sizing: border-box;
  }
  .rightBox {
    display: flex;
    height: 100%;
    box-sizing: border-box;
    flex-direction: column;
    flex: 1;
    .rb-top {
      padding: 20px;
      width: 100%;
      background-color: #fff;
      margin-bottom: 10px;
    }
    .rb-bottom {
      padding: 20px;
      flex: 1;
      overflow: auto;
      width: 100%;
      background-color: #fff;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: center;
  }

}
</style>
